package com.example.demo.service.impl;

import com.example.demo.common.Result;
import com.example.demo.dto.UserLoginDTO;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import com.example.demo.util.JWTUtil;
import com.example.demo.vo.UserInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {
    @Resource    // byName 方式
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    UserMapper userMapper;
    @Override
    public Result doLogin(UserLoginDTO userLoginDTO) {
        System.out.println("username: " + userLoginDTO.getUsername() + " password: " + userLoginDTO.getPassword());
        User user0 = new User();
        user0.setUsername(userLoginDTO.getUsername());
        List<User> userList = userMapper.selectUser(user0);
        if(userList.isEmpty()){
            return Result.fail("登录失败");
        }
        User user = userList.get(0);
        if (user.getPassword() == null || !user.getPassword().equals(userLoginDTO.getPassword())) {
            return Result.fail("登录失败");
        }
        String token = JWTUtil.getToken(user, 7);
        // 操作String类型
        ValueOperations<String, Object> stringOps = redisTemplate.opsForValue();
        String key = "demo_token"+user.getId();
        stringOps.set(key, token);
        redisTemplate.expire(key, 7, TimeUnit.DAYS); //设置7天有效
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        return Result.success(map);
    }

    @Override
    public Result getUserInfo(String token) {
        token = token.substring(7);
        User user0 = JWTUtil.parseToken(token); //令牌中含有id和name
        User user = userMapper.selectUser(user0).get(0);
        UserInfoVO userInfoVO = new UserInfoVO();
        userInfoVO.setUsername(user.getUsername());
        String[] roles = user.getRoles().split(",");
        userInfoVO.setRoles(roles);
        return Result.success(userInfoVO);
    }
}
